package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.FollowBehaviorConstants;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.user.feign.ApAuthorFeign;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author feng js
 */
@Service
@Transactional
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    private ApAuthorFeign apAuthorFeign;
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (dto.getOperation() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"作者信息不能为空");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        ApAuthor apAuthor = apAuthorFeign.findByIdToUser(dto.getAuthorId());
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"没有找到作者信息");
        }

        if (dto.getOperation() == 0) {
            return followByUserId(user,dto.getArticleId(),apAuthor.getUserId());
        } else {
            return followCancelByUserId(user,apAuthor.getUserId());
        }

    }

    @Autowired
   private ApUserFollowMapper apUserFollowMapper;
    @Autowired
   private ApUserFanMapper apUserFanMapper;
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    private ResponseResult followCancelByUserId(ApUser user, Integer followId) {
        ApUserFollow userFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followId).eq(ApUserFollow::getUserId, user.getId()));
        if (userFollow == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "未关注");
        } else {

            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getFansId, user.getId()).eq(ApUserFan::getUserId, followId));
            if (apUserFan == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "不是粉丝");
            } else {
                apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                        .eq(ApUserFan::getFansId,user.getId()).eq(ApUserFan::getUserId,followId));
                apUserFollowMapper.delete(Wrappers.<ApUserFollow>lambdaQuery()
                        .eq(ApUserFollow::getFollowId,followId).eq(ApUserFollow::getUserId,user.getId()));
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        }

    }

    private ResponseResult followByUserId(ApUser user, Long articleId, Integer followId) {
        ApUser loginUser = apUserMapper.selectById(user.getId());
        if (loginUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"关注的用户不存在");
        }
        ApUserFollow userFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery()
                .eq(ApUserFollow::getFollowId, followId).eq(ApUserFollow::getUserId, user.getId()));
        if (userFollow == null) {
            ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getFansId, user.getId()).eq(ApUserFan::getUserId, followId));
            if (apUserFan == null) {
                apUserFan = new ApUserFan();
                apUserFan.setUserId(followId);
                apUserFan.setFansId((long) user.getId());
                apUserFan.setCreatedTime(new Date());
                apUserFan.setIsDisplay(true);
                apUserFan.setLevel((short) 0);
                apUserFan.setIsShieldComment(false);
                apUserFan.setIsShieldLetter(false);
                apUserFanMapper.insert(apUserFan);
            }
            userFollow = new ApUserFollow();
            userFollow.setUserId(user.getId());
            userFollow.setFollowId(followId);
            userFollow.setFollowName(loginUser.getName());
            userFollow.setCreatedTime(new Date());
            userFollow.setLevel((short) 1);
            userFollow.setIsNotice(true);
            apUserFollowMapper.insert(userFollow);

            //将关注行为数据发送到行为服务
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setUserId(user.getId());
            followBehaviorDto.setArticleId(articleId);
            followBehaviorDto.setFollowId(followId);
            kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"已关注");
        }

    }
}
